package com.cai310.lottery.web.controller.user;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.ProjectionList;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.transform.Transformers;
import org.mortbay.log.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import com.cai310.lottery.Constant;
import com.cai310.lottery.common.MessageType;
import com.cai310.lottery.common.PopuType;
import com.cai310.lottery.common.UserWay;
import com.cai310.lottery.entity.user.AgentRelation;
import com.cai310.lottery.entity.user.BankInfo;
import com.cai310.lottery.entity.user.Media;
import com.cai310.lottery.entity.user.Popu;
import com.cai310.lottery.entity.user.User;
import com.cai310.lottery.entity.user.UserInfo;
import com.cai310.lottery.entity.user.UserLogin;
import com.cai310.lottery.service.QueryService;
import com.cai310.lottery.service.ServiceException;
import com.cai310.lottery.service.lottery.EventLogManager;
import com.cai310.lottery.web.controller.GlobalResults;
import com.cai310.lottery.web.controller.WebDataException;
import com.cai310.lottery.web.sso.SsoLoginHolder;
import com.cai310.orm.Pagination;
import com.cai310.orm.XDetachedCriteria;
import com.cai310.utils.CookieUtil;
import com.cai310.utils.DateUtil;
import com.cai310.utils.MD5;
import com.cai310.utils.MessageUtil;
import com.cai310.utils.PropertiesUtil;
import com.cai310.utils.Struts2Utils;
import com.esms.PostMsg;
import com.google.common.collect.Lists;

@Results({
		@Result(name = UserController.FWD_WELCOME, type = "redirectAction", params = { "actionName", "user", "method",
				"welcome" }),
		@Result(name = UserController.EDIT_SUCCESS, type = "redirectAction", params = { "actionName", "user", "method",
				"edit" }), @Result(name = "message", location = "/WEB-INF/content/common/message.ftl") })
public class UserController extends UserBaseController {
	private static final long serialVersionUID = 2300904439118054778L;
	public static final String FWD_WELCOME = "reg_success";
	public static final String EDIT_SUCCESS = "edit_success";
	public static final String LOGIN_TRY_TIMES = "LOGIN_TRY_TIMES";
	public static final String REGIST_IP_KEY = "REGIST_IP_KEY";

	public static final String NEED_CAPTCHA = "needCaptcha";
	public static final String REG_SUCCESS = "register_success";
	private static final String TO_VALID_SUCCESS = "reset";
	public static final int SIMPLE_MAX_TRY_TIMES = 3;
	public static final String CYY_INDEX = Constant.BASEPATH + "/";
	private Pagination pagination = new Pagination(20);

	@Autowired
	@Qualifier("userLoginCache")
	private Cache userLoginCache;

	@Autowired
	@Qualifier("userRegistCache")
	private Cache userRegistCache;

	@Autowired
	@Qualifier("commonQueryCache")
	private Cache commonQueryCache;

	@Resource
	protected EventLogManager eventLogManager;

	@Autowired
	protected QueryService queryService;
	private RegForm regForm;
	private UserInfoForm infoForm;
	private BankForm bankForm;
	private PasswordForm pwdForm;
	private EmailValForm emailValForm;
	private String captcha;
	private UserLogin beforeUserLogin;

	public String index() {
		return welcome();
	}
	public String message() {
		return welcome();
	}
	private String getLoginTryTimesKey() {
		return LOGIN_TRY_TIMES + Struts2Utils.getSession().getId();
	}
 
	private String getRegistKey() {
		String ip = Struts2Utils.getRemoteAddr();
		if (null != ip) {
			String[] ipkey = ip.split("\\.");
			String key = ipkey[0] + "." + ipkey[1];
			return REGIST_IP_KEY + key;
		}
		return null;
	}

	// ip限制
	private boolean addRegistTimes() {
		int tryTimes = getRegistTimes();
		tryTimes++;
		Log.info("IP:" + getRegistKey());
		userRegistCache.put(new Element(getRegistKey(), Integer.valueOf(tryTimes)));
		if (tryTimes >= SIMPLE_MAX_TRY_TIMES) {
			return false;
		}
		return true;
	}

	// ip限制
	private int getRegistTimes() {
		Element el = userRegistCache.get(getRegistKey());
		if (el != null)
			return ((Integer) el.getValue()).intValue();

		return 0;
	}

	private void addLoginTryTimes() {
		int tryTimes = getLoginTryTimes();
		tryTimes++;

		userLoginCache.put(new Element(getLoginTryTimesKey(), Integer.valueOf(tryTimes)));

		if (tryTimes >= SIMPLE_MAX_TRY_TIMES)
			Struts2Utils.setAttribute(NEED_CAPTCHA, true);
	}

	private int getLoginTryTimes() {
		Element el = userLoginCache.get(getLoginTryTimesKey());
		if (el != null)
			return ((Integer) el.getValue()).intValue();

		return 0;
	}

	private void clearLoginTryInfo() {
		userLoginCache.remove(getLoginTryTimesKey());
	}
	/**
	 * 登录
	 */
	public String login() {
		User loginUser = getLoginUser();
		if (loginUser != null) {
			return redirectforward(Boolean.TRUE, "您已经登录!请先退出", null, "message");
		}
		String fwd;
		String type = Struts2Utils.getRequest().getParameter("type");
		String agent = Struts2Utils.getRequest().getParameter("agent");
		if ("quick_login".equals(type)) {
			fwd = "quick-login";
		} else {
			fwd = "login";
		}
		if ("GET".equals(Struts2Utils.getRequest().getMethod())) {// 转向登录页面
			int tryTimes = getLoginTryTimes();
			if (tryTimes >= SIMPLE_MAX_TRY_TIMES) {
				if (Struts2Utils.isAjaxRequest()) {
					Map<String, Object> jsonMap = new HashMap<String, Object>();
					jsonMap.put("success", false);
					jsonMap.put("need_captcha", true);
					Struts2Utils.renderJson(jsonMap);
					return null;
				} else {
					Struts2Utils.setAttribute(NEED_CAPTCHA, true);
				}
			}
			return fwd;
		}

		// 登录操作
		try {
			String userName = Struts2Utils.getParameter("userName");
			if (StringUtils.isBlank(userName))
				throw new WebDataException("用户名不能为空.");
			userName = java.net.URLDecoder.decode(userName.trim(), "UTF-8");

			String password = Struts2Utils.getParameter("password");
			if (StringUtils.isBlank(password))
				throw new WebDataException("密码不能为空.");

			String ipAddress = Struts2Utils.getRemoteAddr();
			logger.info("用户[{}]尝试登录网站,来源IP：{}", userName, ipAddress);

			int tryTimes = getLoginTryTimes();
			if (tryTimes >= SIMPLE_MAX_TRY_TIMES) {
				this.jsonMap.put("need_captcha", true);
				Struts2Utils.setAttribute(NEED_CAPTCHA, true);
				String captcha = Struts2Utils.getParameter("captcha");
				if (StringUtils.isBlank(captcha)) {
					throw new WebDataException("为了您的用户安全，请输入验证码.");
				} else if (!captcha.equals(Struts2Utils.getSession().getAttribute(Constant.LOGIN_CAPTCHA))) {
					throw new WebDataException("验证码错误.");
				}
			}

			// 转化为小写用户名 进行查询 zhuhui motify 2011-05-04
			User user = userManager.getUserBy(userName);

			if (user == null) {
				addLoginTryTimes();
				throw new WebDataException("用户名或密码错误.");
			} else {
				if (null == user.getInfo()) {
					user.setInfo(new UserInfo());
					userManager.saveUser(user);
				}
				if (null == user.getBank()) {
					user.setBank(new BankInfo());
					userManager.saveUser(user);
				}
			}
			if (user.isLocked())
				throw new WebDataException("该账户已被锁定,请联系客服.");

			String pwd = MD5.md5(password.trim()).toUpperCase();
			if (!pwd.equalsIgnoreCase(user.getPassword())) {
				addActionError("用户名或密码错误.");
				addLoginTryTimes();
				return forward(false, fwd);
			} else {
				addActionMessage("登录成功.");
				Struts2Utils.getRequest().removeAttribute(NEED_CAPTCHA);
				clearLoginTryInfo();
				SsoLoginHolder.login(user.getId());

				String redirectUrl = CookieUtil.getCookieByName(Struts2Utils.getRequest(), "redirectUrl");
				if (StringUtils.isBlank(redirectUrl))
					redirectUrl = null;
				Struts2Utils.setAttribute("redirectUrl", redirectUrl);
				if (isAjaxRequest()) {
					return success();
				} else {
					if(StringUtils.isNotBlank(agent)){
						Struts2Utils.sendRedirect(redirectUrl);
						return null;
					}else{
						return redirectforward(Boolean.TRUE, "欢迎您回来," + userName, redirectUrl, "message");
					}
				}
			}
		} catch (WebDataException e) {
			addActionError(e.getMessage());
		} catch (ServiceException e) {
			addActionError(e.getMessage());
		} catch (Exception e) {
			addActionError(e.getMessage());
			logger.error(e.getMessage(), e);
		}
		return forward(false, fwd);
	}
	/**
	 * 会员管理首页
	 * 
	 * @return
	 * @throws WebDataException
	 */
	public String userManeger() throws WebDataException {
		try{
			User loginUser = this.getLoginUser();
			if (null != loginUser) {
				String key = getRequestKey() + loginUser.getId();
				Element el = commonQueryCache.get(key);
				if (el == null) {
					XDetachedCriteria criteria = new XDetachedCriteria(User.class, "m");
					
					ProjectionList propList = Projections.projectionList();
					propList.add(Projections.property("id"), "id");
					propList.add(Projections.property("userName"), "userName");
					propList.add(Projections.property("remainMoney"), "remainMoney");
					propList.add(Projections.property("consumptionMoney"), "consumptionMoney");
					propList.add(Projections.property("createTime"), "createTime");
					propList.add(Projections.property("rebate"), "rebate");
					propList.add(Projections.property("locked"), "locked");
					criteria.setProjection(propList);
					criteria.add(Restrictions.eq("m.agentId", loginUser.getId()));
					criteria.addOrder(Order.desc("m.consumptionMoney"));
					criteria.addOrder(Order.desc("m.id"));
					criteria.setResultTransformer(Transformers.aliasToBean(User.class));
					pagination = queryService.findByCriteriaAndPagination(criteria, pagination);
					el = new Element(key, this.pagination);
					commonQueryCache.put(el);
				} else {
					pagination = (Pagination) el.getValue();
				}
			} else {
				throw new WebDataException("您还未登录,请登录后再操作.");
			}
		} catch (WebDataException e) {
			addActionError(e.getMessage());
		} catch (ServiceException e) {
			addActionError(e.getMessage());
		} catch (Exception e) {
			addActionError(e.getMessage());
			logger.error(e.getMessage(), e);
		}
		return forward(false, "maneger");
	}
	
	/**
	 * 下属查询
	 * 
	 * @return
	 * @throws WebDataException
	 */
	public String seeUser() throws WebDataException {
		User loginUser = this.getLoginUser();
		if (loginUser == null) {
			CookieUtil.addReUrlCookie();
			return GlobalResults.FWD_LOGIN;
		}
		String fwd = "see-user";
		try{
			if (loginUser == null) {
				addActionError("您还没登录,请先登录.");
				return forward(false, fwd);
			}
			String userId = Struts2Utils.getParameter("userId");
			if (StringUtils.isBlank(userId)) {
				addActionError("被操作用户ID为空.");
				return forward(false, fwd);
			}
			User user = userManager.getUser(Long.valueOf(userId));
			if(!user.checkRelation(loginUser)){
				addActionError("您无权操作.");
				return forward(false, fwd);
			}
			Struts2Utils.getRequest().setAttribute("userName",user.getUserName());
			if (null != user) {
				String key = getRequestKey() + user.getId();
				Element el = commonQueryCache.get(key);
				if (el == null) {
					XDetachedCriteria criteria = new XDetachedCriteria(User.class, "m");
					
					ProjectionList propList = Projections.projectionList();
					propList.add(Projections.property("id"), "id");
					propList.add(Projections.property("userName"), "userName");
					propList.add(Projections.property("remainMoney"), "remainMoney");
					propList.add(Projections.property("consumptionMoney"), "consumptionMoney");
					propList.add(Projections.property("createTime"), "createTime");
					propList.add(Projections.property("rebate"), "rebate");
					propList.add(Projections.property("locked"), "locked");
					criteria.setProjection(propList);
					criteria.add(Restrictions.eq("m.agentId", user.getId()));
					criteria.addOrder(Order.desc("m.consumptionMoney"));
					criteria.addOrder(Order.desc("m.id"));
					criteria.setResultTransformer(Transformers.aliasToBean(User.class));
					pagination = queryService.findByCriteriaAndPagination(criteria, pagination);
					el = new Element(key, this.pagination);
					commonQueryCache.put(el);
				} else {
					pagination = (Pagination) el.getValue();
				}
			} else {
				throw new WebDataException("您还未登录,请登录后再操作.");
			}
		} catch (WebDataException e) {
			addActionError(e.getMessage());
		} catch (ServiceException e) {
			addActionError(e.getMessage());
		} catch (Exception e) {
			addActionError(e.getMessage());
			logger.error(e.getMessage(), e);
		}
		return forward(false, fwd);
	}
	
	
	public static void main(String[] args) {
		double money = 1.75;
		String moneyStr = ""+money;
		if(moneyStr.indexOf(".")!=-1){
			String[] moneArr = moneyStr.split("\\.");
			int i = 0;
		}else{
			//0
		}
		System.out.print(Integer.valueOf(money+""));
	}
	/**
	 * 操作会员佣金
	 * 
	 * @return
	 * @throws WebDataException
	 */
	public String oprRebate() {
		User loginUser = getLoginUser();
		if (loginUser == null) {
			CookieUtil.addReUrlCookie();
			return GlobalResults.FWD_LOGIN;
		}
		String fwd = "opr-rebate";
		if (loginUser == null) {
			addActionError("您还没登录,请先登录.");
			return forward(false, fwd);
		}
		String userId = Struts2Utils.getParameter("userId");
		if (StringUtils.isBlank(userId)) {
			addActionError("被操作用户ID为空.");
			return forward(false, fwd);
		}
		if ("GET".equals(Struts2Utils.getRequest().getMethod())) {// 转向登录页面
			User user = userManager.getUser(Long.valueOf(userId));
			if(!user.getAgentId().equals(loginUser.getId())){
				addActionError("您无权操作.");
				return forward(false, fwd);
			}
			String moneyStr = ""+user.getRebate();
			if(moneyStr.indexOf(".")!=-1){
				String[] moneArr = moneyStr.split("\\.");
				if(moneArr.length!=2){
					addActionError("返点出错.");
					return forward(false, fwd);
				}
				Struts2Utils.getRequest().setAttribute("rebate1", Integer.valueOf(moneArr[0]));
				Struts2Utils.getRequest().setAttribute("rebate2", Integer.valueOf(moneArr[1]));
			}else{
				Struts2Utils.getRequest().setAttribute("rebate1", Integer.valueOf(0));
				Struts2Utils.getRequest().setAttribute("rebate2", Integer.valueOf(0));
			}
			NumberFormat nf = NumberFormat.getInstance();
			nf.setMinimumFractionDigits(2);
			nf.setMaximumFractionDigits(2);
			Struts2Utils.getRequest().setAttribute("my_rebate", null ==loginUser.getRebate()?0:nf.format(loginUser.getRebate()));
			Struts2Utils.getRequest().setAttribute("opr_user_name", user.getUserName());
			Struts2Utils.getRequest().setAttribute("opr_user_id", user.getId());
			return forward(true, fwd);
		}

		// 登录操作
		try {
			User user = userManager.getUser(Long.valueOf(userId));
			if(!user.getAgentId().equals(loginUser.getId())){
				addActionError("您无权操作.");
				return forward(false, fwd);
			}
			String rebate1 = Struts2Utils.getParameter("rebate1");
			String rebate2 = Struts2Utils.getParameter("rebate2");
			if(StringUtils.isBlank(rebate1)){
				addActionError("返点1还没设置.");
				return forward(false, fwd);
			}
			if(StringUtils.isBlank(rebate2)){
				addActionError("返点2还没设置.");
				return forward(false, fwd);
			}
			Double rebate = Double.valueOf(rebate1.trim()+"."+rebate2.trim());
			if(null ==loginUser.getRebate()){
				addActionError("帐号返点异常.");
				return forward(false, fwd);
			}
			if(rebate<0){
				addActionError("返点不能小于0，请调整.");
				return forward(false, fwd);
			}
			if(loginUser.getRebate()-rebate<0){
				addActionError("子帐号返点不能大于本账号，请调整.");
				return forward(false, fwd);
			}
			DetachedCriteria criteria = DetachedCriteria.forClass(User.class, "m");
			criteria.add(Restrictions.eq("m.agentId", user.getId()));
			List<User> underUserList = this.queryService.findByDetachedCriteria(criteria);
			if(null!=underUserList&&!underUserList.isEmpty()){
				Double underUserRebate = Double.valueOf(0);
				for (User underUser : underUserList) {
					if(underUser.getRebate()-underUserRebate>0){
						underUserRebate = underUser.getRebate();
					}
				}
				if(underUserRebate - rebate>0){
					addActionError("帐号返点不能小于子账号，请调整.");
					return forward(false, fwd);
				}
			}
			user.setRebate(rebate);
			user = userManager.saveUser(user);
			addActionMessage("修改成功.");
			return success();
		} catch (ServiceException e) {
			addActionError(e.getMessage());
		} catch (Exception e) {
			addActionError(e.getMessage());
			logger.error(e.getMessage(), e);
		}
		return forward(false, fwd);
	}
	
	/**
	 * 操作会员佣金
	 * 
	 * @return
	 * @throws WebDataException
	 */
	public String oprMoney() {
		User loginUser = getLoginUser();
		if (loginUser == null) {
			CookieUtil.addReUrlCookie();
			return GlobalResults.FWD_LOGIN;
		}
		String fwd = "opr-money";
		if (loginUser == null) {
			addActionError("您还没登录,请先登录.");
			return forward(false, fwd);
		}
		String userId = Struts2Utils.getParameter("userId");
		if (StringUtils.isBlank(userId)) {
			addActionError("被操作用户ID为空.");
			return forward(false, fwd);
		}
		if ("GET".equals(Struts2Utils.getRequest().getMethod())) {// 转向登录页面
			User user = userManager.getUser(Long.valueOf(userId));
			if(!user.getAgentId().equals(loginUser.getId())){
				addActionError("您无权操作.");
				return forward(false, fwd);
			}
			NumberFormat nf = NumberFormat.getInstance();
			nf.setMinimumFractionDigits(2);
			nf.setMaximumFractionDigits(2);
			Struts2Utils.getRequest().setAttribute("my_money", null ==loginUser.getRemainMoney()?0:nf.format(loginUser.getRemainMoney()));
			Struts2Utils.getRequest().setAttribute("opr_money", null ==user.getRemainMoney()?0:nf.format(user.getRemainMoney()));
			Struts2Utils.getRequest().setAttribute("opr_user_name", user.getUserName());
			Struts2Utils.getRequest().setAttribute("opr_user_id", user.getId());
			return forward(true, fwd);
		}

		// 登录操作
		try {
			User user = userManager.getUser(Long.valueOf(userId));
			if(!user.getAgentId().equals(loginUser.getId())){
				addActionError("您无权操作.");
				return forward(false, fwd);
			}
			Double oprMoney = null;
			try {
				String money = Struts2Utils.getParameter("oprMoney");
				oprMoney = Double.valueOf(money.trim());
				///xxxx-c修改。用户输入负数的时候会出现透支的情况。
				oprMoney =  BigDecimal.valueOf(oprMoney).abs().doubleValue();
			}
		    catch (Exception e) {
		    	addActionError("操作金额出错.");
				return forward(false, fwd);	
			}
			if(loginUser.getRemainMoney().doubleValue()-oprMoney<0){
				addActionError("子帐号调整不能大于本余额，请调整.");
				return forward(false, fwd);
			}
			synchronized (Constant.DRAWING) {
				userManager.agentOprUserMoney(loginUser, user, BigDecimal.valueOf(oprMoney).abs());
			}
			addActionMessage("修改成功.");
			return success();
		} catch (ServiceException e) {
			addActionError(e.getMessage());
		} catch (Exception e) {
			addActionError(e.getMessage());
			logger.error(e.getMessage(), e);
		}
		return forward(false, fwd);
	}
	
	/**
	 * 登录会员中心首页
	 * 
	 * @return
	 * @throws WebDataException
	 */
	public String userCenter() throws WebDataException {
		User loginUser = getLoginUser();
		if (loginUser == null) {
			CookieUtil.addReUrlCookie();
			return GlobalResults.FWD_LOGIN;
		}
		if (null != loginUser) {
			UserInfoForm userInfoForm = new UserInfoForm();
			// 用户账户信息
			NumberFormat nf = NumberFormat.getInstance();
			nf.setMinimumFractionDigits(2);
			nf.setMaximumFractionDigits(2);
			Struts2Utils.setAttribute("userInfoForm", userInfoForm);
		} else {
			throw new WebDataException("您还未登录,请登录后再操作.");
		}
		return "index";
	}

	/**
	 * 退出登录
	 */
	public String logout() {
		SsoLoginHolder.logout();
		// 生成‘单点登录-退出’的URL。Add By Peter
		String siteId = "hclotto";
		String serviceId = "logoutNotify";
		String key = "55662233";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		String trace = sdf.format(new Date());
		if (trace.length() > 16) {
			trace = trace.substring(0, 16);
		}

		String data = "SiteId=" + siteId + "&ServiceId=" + serviceId + "&TraceNo=" + trace;
		String md5 = MD5.md5((data + key).toLowerCase()).toLowerCase();
		String url = "http://www.cai310.net/portal/" + serviceId + ".htm?" + data + "&SignType=MD5&Sign=" + md5
				+ "&jsoncallback=?";
		this.jsonMap.put("sliUrl", url);

		Struts2Utils.getSession().setAttribute("user", null);
		Struts2Utils.getSession().setAttribute("password", null);
		if (isAjaxRequest()) {
			this.jsonMap.put("sloUrl", url);
			return success();
		} else {
			Struts2Utils.setAttribute("sloUrl", url);
			return redirectforward(Boolean.TRUE, "您已经安全的退出", null, "message");
		}
	}

	/**
	 * 进入注册页面
	 */
	public String register() {
		User loginUser = this.getLoginUser();
		return "register";
	}
	/**
	 * 进入注册页面
	 */
	public String reg() {
		CookieUtil.addReUrlCookie();
		if(StringUtils.isNotBlank(Struts2Utils.getParameter("i"))){
			try{
				String introductionId = Struts2Utils.getParameter("i");
				User loginUser = userManager.getUser(Long.valueOf(introductionId));
				if(null==loginUser){
					throw new WebDataException("找不到响应的介绍人.");
				}
				CookieUtil.addIntroductionIdCookie(introductionId);
			}catch(Exception e){
				logger.error(e.getMessage(), e);//出错不存储介绍人
			}
		}
		weitePopu();
		return "reg";
	}

	/**
	 * 注册成功后页面
	 */
	public String regSuccess() {
		User user = (User) SsoLoginHolder.getLoggedUser();
		Struts2Utils.getRequest().setAttribute("user", user);
		return "regSuccess";
	}
	public String welcome(){
		weitePopu();
		return redirectforward(Boolean.TRUE, "欢迎您的到来!", Constant.BASEPATH + "/", "message");
		
	}
	public void weitePopu(){
		try{
			String mid = Struts2Utils.getParameter("mid");
			writeMid(mid);
			String aid = Struts2Utils.getParameter("aid");
			writeAid(aid);
			//记录
			Popu popu = this.getPopu(PopuType.WEB);
			if(null!=popu){
					userManager.savePopu(popu);
			}
		}catch(Exception e){
			logger.error("注册的时候发生媒体来源异常"+e.getMessage());
		}
	}
	public void writeMid(String mid){
		int   SECONDS_PER_YEAR   =   60*60*24*365;   
		if(StringUtils.isNotBlank(mid)){
			try{
				Media media = userManager.getMedia(Long.valueOf(mid));
				if(null!=media){
					CookieUtil.addCookie(Struts2Utils.getResponse(), "mid", ""+media.getId(), SECONDS_PER_YEAR);
				}else{
					CookieUtil.addCookie(Struts2Utils.getResponse(), "mid", "0", SECONDS_PER_YEAR);
				}
			}catch(Exception e){
				logger.error("注册的时候发生媒体来源异常"+e.getMessage());
				CookieUtil.addCookie(Struts2Utils.getResponse(), "mid", "0", SECONDS_PER_YEAR);
			}
		}
	}
	public void writeAid(String aid){
		int   SECONDS_PER_YEAR   =   60*60*24*365;   
		if(StringUtils.isNotBlank(aid)){
			try{
				CookieUtil.addCookie(Struts2Utils.getResponse(), "aid", ""+Long.valueOf(aid), SECONDS_PER_YEAR);
			}catch(Exception e){
				logger.error("注册的时候发生媒体来源异常"+e.getMessage());
				CookieUtil.addCookie(Struts2Utils.getResponse(), "aid", "0", SECONDS_PER_YEAR);
			}
		}
	}
	/**
	 * 注册操作
	 */
	final String forbidString = "system,bcmm,admin,管理员";

	public String create() throws WebDataException {
		String fwd = "register";
		String register_type=Struts2Utils.getParameter("register_type");
		try{
			if (regForm == null) {
				throw new WebDataException("注册信息为空.");
			}
			if (StringUtils.isBlank(regForm.getUserName())) {
				throw new WebDataException("用户名为空.");
			}
			String captcha = Struts2Utils.getParameter("captcha");
			if (StringUtils.isBlank(captcha)) {
				throw new WebDataException("请输入验证码.");
			} else if (!captcha.equals(Struts2Utils.getSession().getAttribute(Constant.LOGIN_CAPTCHA))) {
				throw new WebDataException("验证码错误.");
			}
			//判读用户名是否重复
			String userName = java.net.URLDecoder.decode(this.regForm.getUserName().trim(), "utf-8");
			User userTemp = userManager.getUserBy(userName);
			if (userTemp != null && userTemp.getUserName().equals(userName.toLowerCase())) {
				throw new WebDataException("注册用户名重复.请更改.");
			}
			User user = new User();
			////增加用户媒体来源信息
			String mid = CookieUtil.getCookieByName(Struts2Utils.getRequest(), "mid");
			if(StringUtils.isNotBlank(mid)){
				try{
					Media media = userManager.getMedia(Long.valueOf(mid));
					if(null!=media){
						user.setMid(media.getId());
					}else{
						user.setMid(0L);
					}
				}catch(Exception e){
					logger.error("注册的时候发生媒体来源异常"+e.getMessage());
				}
			}
			user.setUserWay(UserWay.WEB);
			user.setUserName(userName.toLowerCase());
			user.setLocked(User.NO_LOCK_STATUS);
			user.setRemainMoney(BigDecimal.ZERO);
			String relation = null;
			if(StringUtils.isNotBlank(register_type)){
				if("0".equals(register_type)){
					User loginUser = this.getLoginUser();
					if(null==loginUser)throw new WebDataException("您还没登录请先登录.");
					if(StringUtils.isBlank(loginUser.getRelation())||"0".equals(loginUser.getRelation().trim())){
						///没有上级的
						relation = loginUser.getId()+"";
					}else{
						relation = loginUser.getRelation()+"-"+loginUser.getId();
					}
					Double rebate = Double.valueOf(this.regForm.getRebate1()+"."+this.regForm.getRebate2());
					if(null ==loginUser.getRebate()){
						addActionError("帐号返点异常.");
						return forward(false, "register");
					}
					if(loginUser.getRebate()-rebate<0){
						addActionError("子帐号返点不能大于本账号，请调整.");
						return forward(false, "register");
					}
					user.setPassword(MD5.md5("123456").toUpperCase());
					user.setAgentId(loginUser.getId());
					user.setRelation(relation);
					user.setRebate(rebate);
					UserInfo info = new UserInfo();
					BankInfo bank = new BankInfo();
					user.setBank(bank);
					user.setInfo(info);
					user = userManager.saveUser(user, info, bank);
					addActionMessage("注册成功.");
				}
			}else{
				///不是在会员中心指定下属
				fwd = "reg";
				String introductionId = CookieUtil.getIntroductionIdCookie();
				if(StringUtils.isBlank(introductionId)){
					introductionId = Constant.SITE_BAODI_USER_ID+"";///如果没有就吧他转为网站保底账户的ID
				}
				User loginUser = userManager.getUser(Long.valueOf(introductionId));
				if(null==loginUser){
					throw new WebDataException("找不到响应的介绍人.");
				}
				if(StringUtils.isBlank(loginUser.getRelation())||"0".equals(loginUser.getRelation().trim())){
					///没有上级的
					relation = loginUser.getId()+"";
				}else{
					relation = loginUser.getRelation()+"-"+loginUser.getId();
				}
				Double rebate = Double.valueOf(0);
				if(null ==loginUser.getRebate()){
					addActionError("帐号返点异常.");
					return forward(false, fwd);
				}
				if(loginUser.getRebate()-rebate<0){
					addActionError("子帐号返点不能大于本账号，请调整.");
					return forward(false, "register");
				}
				if (StringUtils.isBlank(regForm.getPassword())) {
					throw new WebDataException("密码为空.");
				}
				if (StringUtils.isBlank(regForm.getConfirmPassword())) {
					throw new WebDataException("确认密码为空.");
				}
				if (!regForm.getConfirmPassword().trim().equals(regForm.getPassword().trim())) {
					throw new WebDataException("确认密码和密码不一致.");
				}
				user.setPassword(MD5.md5(regForm.getPassword().trim()).toUpperCase());
				user.setAgentId(loginUser.getId());
				user.setRelation(relation);
				user.setRebate(rebate);
				UserInfo info = new UserInfo();
				BankInfo bank = new BankInfo();
				user.setBank(bank);
				user.setInfo(info);
				user = userManager.saveUser(user, info, bank);
				addActionMessage("注册成功.");
				SsoLoginHolder.login(user.getId());
				String redirectUrl = CookieUtil.getCookieByName(Struts2Utils.getRequest(), "redirectUrl");
				if (StringUtils.isBlank(redirectUrl))
					redirectUrl = null;
				Struts2Utils.setAttribute("redirectUrl", redirectUrl);
				if (isAjaxRequest()) {
					return success();
				} else {
					return redirectforward(Boolean.TRUE,  userName, redirectUrl, "regSuccess");
				}
			}
		} catch (WebDataException e) {
			addActionError(e.getMessage());
		} catch (ServiceException e) {
			addActionError("网络错误，注册失败，请稍后再试");
		} catch (Exception e) {
			addActionError("网络错误，注册失败，请稍后再试");
			logger.error(e.getMessage(), e);
		}
		if(StringUtils.isBlank(register_type)){
			fwd = "reg";
		}
		return forward(false, fwd);
	}

	public String resetPasswd() {
		return "passwd-reset";
	}
	public String resetPasswordByEmail() {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		User loginUser = getLoginUser();
		if (loginUser != null) {
			return redirectforward(Boolean.TRUE, "您已经登录!请先退出", null, "message");
		}
		if ("GET".equals(Struts2Utils.getRequest().getMethod())) {// 转向登录页面
			return "user-password-reset-email";
		}
		String userName = Struts2Utils.getParameter("userName");
		String newuserName = null;
		try {
			newuserName = java.net.URLDecoder.decode(userName, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			jsonMap.put("success", false);
			jsonMap.put("msg", "重置密码失败，请检查用户名及注册邮箱!");
		}
		String email = Struts2Utils.getParameter("email");
		if (StringUtils.isNotBlank(newuserName) && StringUtils.isNotBlank(email)) {
			try {
				if (userManager.resetPasswordAndSendEmail(newuserName, email)) {
					jsonMap.put("success", true);
					jsonMap.put("msg", "重置密码成功，新密码已发送至邮箱!");
				} else {
					jsonMap.put("success", false);
					jsonMap.put("msg", "重置密码失败，请检查用户名及注册邮箱!");
				}
			} catch (Exception e) {
				e.printStackTrace();
				jsonMap.put("success", false);
				jsonMap.put("msg", "重置密码失败，请检查用户名及注册邮箱!");
			}
		}
		Struts2Utils.renderJson(jsonMap);
		return null;
	}
	public String updatePwd() {
		User user = this.getLoginUser();
		HashMap map = new HashMap();
		if (user == null) {
			map.put("success", false);
			map.put("msg", "您尚未登录!");
			map.put("url", Struts2Utils.getRequest().getContextPath() + "/index.html");
			Struts2Utils.renderJson(map);
		} else {
			try {
				String password = regForm.getOldpassword();
				if(StringUtils.isBlank(password)){
					map.put("success", false);
					map.put("msg", "旧密码不能为空!");
					Struts2Utils.renderJson(map);
					return null;
				}
				if(!(MD5.md5(password.trim()).equals(user.getPassword()))){
					map.put("success", false);
					map.put("msg", "旧密码不正确!");
					Struts2Utils.renderJson(map);
					return null;
				}
				user.setPassword(MD5.md5(regForm.getPassword().trim()).toUpperCase());

				userManager.saveUser(user);
				Struts2Utils.getRequest().getSession().setAttribute("user", user);
				map.put("success", true);
				map.put("msg", "密码修改成功!");
				Struts2Utils.renderJson(map);
			} catch (Exception e) {
				e.printStackTrace();
				map.put("success", false);
				map.put("msg", "密码修改失败!");
				Struts2Utils.renderJson(map);
			}

		}
		return null;
	}

	//
	/**
	 * 更新用户个人信息
	 * 
	 * @throws WebDataException
	 */
	public String updateInfo() throws WebDataException {
		User loginUser = getLoginUser();
		if (loginUser == null) {
			CookieUtil.addReUrlCookie();
			return GlobalResults.FWD_LOGIN;
		}
		try {
			if (loginUser == null)
				throw new WebDataException("您还未登录,请登录后再操作.");

			User user = userManager.getUser(loginUser.getId());

			UserInfo info = user.getInfo();
			if (StringUtils.isNotBlank(regForm.getIdCard())) {
				if(StringUtils.isBlank(info.getIdCard())){
					info.setIdCard(regForm.getIdCard());
				}else{
					throw new WebDataException("身份证已经填写，如要修改请联系客服.");
				}
			}else{
				throw new WebDataException("身份证不能为空，请修改.");
			}
			
			if (StringUtils.isNotBlank(regForm.getEmail())) {
				if(StringUtils.isBlank(info.getEmail())){
					info.setEmail(regForm.getEmail());
				}else{
					throw new WebDataException("EMAIL已经填写，如要修改请联系客服.");
				}
			}else{
				throw new WebDataException("EMAIL不能为空，请修改.");
			}
			
			if (StringUtils.isNotBlank(regForm.getPhoneNumber())) {
				if(StringUtils.isBlank(info.getMobile())){
					info.setMobile(regForm.getPhoneNumber());
				}else{
					throw new WebDataException("手机号码已经填写，如要修改请联系客服.");
				}
			}else{
				throw new WebDataException("手机号码不能为空，请修改.");
			}
			
			if (StringUtils.isNotBlank(regForm.getRealName())) {
				if(StringUtils.isBlank(info.getRealName())){
					String realName = java.net.URLDecoder.decode(regForm.getRealName(), "UTF-8");
					info.setRealName(realName);
				}else{
					throw new WebDataException("手机号码已经填写，如要修改请联系客服.");
				}
			}else{
				throw new WebDataException("手机号码不能为空，请修改.");
			}
			userManager.saveUserInfo(info);

		} catch (WebDataException e) {
			addActionError(e.getMessage());
		} catch (ServiceException e) {
			addActionError(e.getMessage());
		} catch (Exception e) {
			addActionError(e.getMessage());
			logger.error(e.getMessage(), e);
		}
		addActionMessage("修改资料成功.");

		if (null != infoForm && null != infoForm.getFrom()) {
			return redirectforward(Boolean.TRUE, "账号信息已完善,请充值!", Constant.BASEPATH + "/user/fund!" + infoForm.getFrom()
					+ ".action", "message");
		}
		return toValidateAccount();
	}

	/**
	 * 检查旧密码是否唯一
	 * 
	 * @return
	 */
	public String checkOldPasswordAble() {
		User user = this.getLoginUser();

		if (user == null) {
			try {
				throw new WebDataException("您尚未登录!");
			} catch (WebDataException e) {
				e.printStackTrace();
			}
		}
		String oldPassword = MD5.md5(regForm.getOldpassword());
		String password = user.getPassword();
		HashMap map = new HashMap();
		if (oldPassword.equals(password)) {
			map.put("success", true);
			Struts2Utils.renderJson(map);
		} else {
			map.put("success", false);
			Struts2Utils.renderJson(map);
		}

		return null;
	}

	/**
	 * 检查用户名是否唯一
	 * 
	 * @return
	 */
	public String checkUserRegAble() {
		User user = this.getLoginUser();
		String userName = null;
		try {
			userName = java.net.URLDecoder.decode(this.regForm.getUserName().trim(), "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		Map<String, Object> map = new HashMap<String, Object>();
		user = userManager.getUserBy(userName);
        if (user == null) {
				map.put("success", true);
				map.put("userName", userName);
				Struts2Utils.renderJson(map);
	    } else {
				map.put("success", false);
				map.put("msg", "registered");
				Struts2Utils.renderJson(map);
		}

		return null;
	}

	/**
	 * 检查验证码是否匹配
	 * 
	 * @return
	 */
	public String checkCodeRegAble() {
		String captcha = (String) Struts2Utils.getSession().getAttribute(Constant.LOGIN_CAPTCHA);
		Map<String, Object> map = new HashMap<String, Object>();
		if (captcha != null && captcha.equals(this.captcha)) {
			map.put("success", true);
			Struts2Utils.renderJson(map);
		} else {
			map.put("success", false);
			Struts2Utils.renderJson(map);
		}
		return null;
	}

	/**
	 * 查看是否登录
	 */
	public String checkLogin() {
		User user = this.getLoginUser();
		if (null != user) {
			UserInfoForm userInfoForm = new UserInfoForm();
			if (StringUtils.isBlank(user.getUserName())) {
				user = userManager.getUser(user.getId());
				user.setUserName("" + user.getId());
				userManager.saveUser(user);
			}
			userInfoForm.setUserName(StringUtils.isBlank(user.getUserName()) ? "&nbsp;" : this.getLoginUser()
					.getUserName().trim());

			NumberFormat nf = NumberFormat.getInstance();
			nf.setMinimumFractionDigits(2);
			nf.setMaximumFractionDigits(2);
			userInfoForm.setDefaultAccountRemainMoney(user == null ? nf.format(BigDecimal.ZERO) : nf
					.format(user.getRemainMoney()));

			Struts2Utils.getRequest().getSession().setAttribute("user", user);

			Map<String, Object> map = new HashMap<String, Object>();
			map.put("success", true);
			map.put("info", userInfoForm);
			Struts2Utils.renderJson(map);
		} else {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("success", false);
			map.put("info", "");
			map.put("lastlogin_time", DateUtil.dateToStr(new Date()));
			Struts2Utils.renderJson(map);
		}
		return null;
	}

	/**
	 * 转向账号设置页面
	 * 
	 * @return
	 * @throws WebDataException
	 */
	public String toValidateAccount() throws WebDataException {
		User loginUser = getLoginUser();
		if (loginUser == null)
			throw new WebDataException("您还未登录,请登录后再操作.");

		User user = userManager.getUser(this.getLoginUser().getId());
		if (user.getInfo() == null) {
			UserInfo info = new UserInfo();
			userManager.saveUser(user, info, null);
		}

		if (user.getBank() == null) {
			BankInfo bank = new BankInfo();
			userManager.saveUser(user, null, bank);
		}
		Struts2Utils.getRequest().setAttribute("user", user);
		return TO_VALID_SUCCESS;
	}

	

	
	/**
	 * 发送短信验证
	 * 
	 * @return
	 */
	public String toMsgValid() {

		Map<String, Object> result = new HashMap<String, Object>();
		User user = this.getLoginUser();
		if (null == user) {
			result.put("msg", "您还没登录。请先登录。");
			result.put("success", false);
			Struts2Utils.renderJson(result);
			return null;
		}
		String mobile = user.getInfo().getMobile();
		if (StringUtils.isBlank(mobile)) {
			result.put("msg", "请完善基本信息手机号，再进行验证。");
			result.put("success", false);
			Struts2Utils.renderJson(result);
			return null;
		}
		if (null!=user.getValidatedPhoneNo()&&user.getValidatedPhoneNo()) {
			result.put("msg", "你的帐号已经验证，本次验证无效!");
			result.put("success", false);
			Struts2Utils.renderJson(result);
			return null;
		}
		try{
			// 保存验证信息
			userManager.SendRandomMessage(user, mobile, MessageType.CHECKPHONE);
			
		}catch(Exception e){
			logger.error(e.getMessage());
			result.put("msg", e.getMessage());
			result.put("success", false);
			Struts2Utils.renderJson(result);
			return null;
		}
		return success();
	}

	/**
	 * 接收短信验证
	 * 
	 * @return
	 */
	public String msgValid() {
		if (!isAjaxRequest()) {
			CookieUtil.addReUrlCookie();
			return GlobalResults.FWD_LOGIN;
		}
		Map<String, Object> result = new HashMap<String, Object>();

		String msgCode = Struts2Utils.getParameter("msgCode");

		if (StringUtils.isBlank(msgCode)) {
			result.put("msg", "请输入验证码。");
			result.put("success", false);
			Struts2Utils.renderJson(result);
			return null;
		}

		User user = this.getLoginUser();
		String mobile = user.getInfo().getMobile();
		if (StringUtils.isBlank(mobile)) {
			result.put("msg", "请完善基本信息手机号，再进行验证。");
			result.put("success", false);
			Struts2Utils.renderJson(result);
			return null;
		}
		if (null!=user.getValidatedPhoneNo()&&user.getValidatedPhoneNo()) {
			result.put("msg", "你的帐号已经验证，本次验证无效!");
			result.put("success", false);
			Struts2Utils.renderJson(result);
			return null;
		}
		try {
			userManager.userRandomMessage(mobile, MessageType.CHECKPHONE,Integer.valueOf(msgCode));
			result.put("msg", "短信验证成功");
			result.put("success", true);
		} catch (ServiceException e) {
			result.put("msg", "短信验证失败,请输入正确的验证码!");
			result.put("success", false);
		}
		Struts2Utils.renderJson(result);
		return null;
	}
	

	/**
	 * 判断日期
	 * 
	 * @param oldDate
	 * @param day
	 * @return
	 */
	private boolean getBeforeAfterDay(Date oldDate, Date curDate, int day) {
		Calendar creDate = Calendar.getInstance();
		creDate.setTime(oldDate);
		int year = creDate.get(Calendar.YEAR);
		int month = creDate.get(Calendar.MONTH);
		int oldDay = creDate.get(Calendar.DAY_OF_MONTH);
		int newDay = oldDay + day;
		creDate.set(Calendar.YEAR, year);
		creDate.set(Calendar.MONTH, month);
		creDate.set(Calendar.DAY_OF_MONTH, newDay);

		if (creDate.getTime().after(curDate))
			return true;
		else
			return false;
	}

	/**
	 * 设置短信接口信息
	 * 
	 * @return
	 */
	private PostMsg setPostMsg() {
		HashMap map = PropertiesUtil.readProperties("msg-config.properties");
		String username = (String) map.get("username");
		String password = (String) map.get("password");
		String cmIP = (String) map.get("cmIP");
		int cmPort = Integer.parseInt((String) map.get("cmPort"));
		String wsIP = (String) map.get("wsIP");
		int wsPort = Integer.parseInt((String) map.get("wsPort"));

		PostMsg msg = new PostMsg(username, password);
		msg.getCmHost().setHost(cmIP, cmPort);
		msg.getWsHost().setHost(wsIP, wsPort);
		return msg;
	}

	/**
	 * @return {@link #regForm}
	 */
	public RegForm getRegForm() {
		return regForm;
	}

	/**
	 * @param regForm
	 *            the {@link #regForm} to set
	 */
	public void setRegForm(RegForm regForm) {
		this.regForm = regForm;
	}

	/**
	 * @return {@link #infoForm}
	 */
	public UserInfoForm getInfoForm() {
		return infoForm;
	}

	/**
	 * @param infoForm
	 *            the {@link #infoForm} to set
	 */
	public void setInfoForm(UserInfoForm infoForm) {
		this.infoForm = infoForm;
	}

	/**
	 * @return {@link #bankForm}
	 */
	public BankForm getBankForm() {
		return bankForm;
	}

	/**
	 * @param bankForm
	 *            the {@link #bankForm} to set
	 */
	public void setBankForm(BankForm bankForm) {
		this.bankForm = bankForm;
	}

	/**
	 * @return {@link #pwdForm}
	 */
	public PasswordForm getPwdForm() {
		return pwdForm;
	}

	/**
	 * @param pwdForm
	 *            the {@link #pwdForm} to set
	 */
	public void setPwdForm(PasswordForm pwdForm) {
		this.pwdForm = pwdForm;
	}

	public EmailValForm getEmailValForm() {
		return emailValForm;
	}

	public void setEmailValForm(EmailValForm emailValForm) {
		this.emailValForm = emailValForm;
	}

	public Pagination getPagination() {
		return pagination;
	}

	public void setPagination(Pagination pagination) {
		this.pagination = pagination;
	}
	public String getCaptcha() {
		return captcha;
	}
	public void setCaptcha(String captcha) {
		this.captcha = captcha;
	}

}
